<?php
namespace Cyfy\Modules\Cyfy;

/**
 * Cyfy module class.
 *
 * Core functions for showing content and accessing blocks and ajax calls, which are neccessary for the system.
 *
 * @author Dandelion
 * @version 0.1
 */
class Module extends \Cyfy\Module
{	
    /**
     * Ajax request.
     */
	static public function ajax($name)
	{
		switch($name)
		{
			case "loadBlocksList":
				return \Cyfy\Blocks :: blocksListClass($_POST["class"]);
			case "getBlock":
                \Cyfy\Blocks :: $forcedShow = true;
                return \Cyfy\Blocks :: getBlock($_POST["class"], $_POST["block"]);
            default:
                return false;
		}
	}
  
    /**
     * Blocks.
     * Cyfy's only block is CONTENT.
     */	
	static public function blocks($name="")
    {
        switch($name)
        {
            case "content":
                return self :: load(\Cyfy\Cyfy :: $query); 
                
            case "":
                return array("content"=> \Cyfy\Cyfy :: t("Content"));
                
            default:
                return false;
        }
    }
    
    /**
     * Starter
     */
    
    static public function start()
    {
        \Cyfy\Cyfy ::  JavaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Cyfy/cyfy.js"), "file", "header");    
    }
    
    /**
     * Loads the contents from the virtual filesystem.
     * 
     * @param  string The URL
     * @return string HTML content
     */
    static public function load($path, $fid = 0)
    {
        // if classic
        if($fid == 0)
        {
            $result = \dibi :: query("SELECT [name], [module], [id], [permission] FROM [:cyfy:Cyfy-filesystem] WHERE [path] = %s LIMIT 1", $path);
        }
        // ID known
        else
        {
            $result = \dibi :: query("SELECT [name], [module], [id], [permission] FROM [:cyfy:Cyfy-filesystem] WHERE [fid] = %i LIMIT 1", $fid);
        }
        
        // not found
        if(count($result) == 0)
        {
            // try by regular
            return self :: loadRegex($path);
        }
        $filesystem = $result -> fetch();
        // permission exists?
        if($filesystem["permission"])
        {
            // has user permission?
            if(!\Cyfy\Cyfy ::  permission($filesystem["module"], $filesystem["permission"]))
            {
                \Cyfy\Cyfy ::  noPermission();
                return false;
            }
        }
        
        // Sets the title
        \Cyfy\Template :: setTitle($filesystem["name"]);
        
        // Gets the content from a static method
        $class = '\Cyfy\Modules\\' . $filesystem["module"] . "\Module";
        
        \Cyfy\Log :: write("Loading FS:" .  $filesystem["module"] . " " . $filesystem["id"]);
        return $class :: get($filesystem["id"]);    
    }
    
    /**
     * Tries to load the content while trying the regex in the rows
     * @param string Path
     * @return string HTML content
     */
    static private function loadRegex($path)
    { 
        $fid = 0; // filesystem ID
        
        $result = \dibi :: query("SELECT [fid],[path] FROM [:cyfy:Cyfy-filesystem]");

        // Going through all filesystem things until it reachs the right one
        // It's quite slow... does anybody know a better one?    
        foreach($result as $fs){
            if(preg_match('/^'.$fs["path"].'$/', $path)){
                \Cyfy\Cyfy ::  $realQuery = $fs["path"];
                $fid = $fs["fid"];
                break;
            }      
        }
    
        // If nothing found:
        if($fid==0)
        {
            // if errors enabled and correction for loops
            if(\Cyfy\Modules :: isEnabled('Errors') && $path != "error/404")
            {   
                $_SESSION["404url"] = $path;
                \Cyfy\Cyfy :: redirectTo('error/404');
            }
            die ("Page not found.");
        }
        return self :: load('', $fid);
    }
}
